package com.rory.controller;

import com.rory.exception.BaseObjException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * class: BaseController.
 * Created by Rory on 2016/11/14.
 * use:  基础controller.
 * other:  .
 */
public abstract class BaseController {
    /**
     * 全局日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 定义统一处理异常方法
     * @param request
     * @param response
     * @param ex
     * @throws IOException
     */
    @ExceptionHandler
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        if(ex instanceof BaseObjException){
            logger.error("发生自定义异常:"+ ex.getMessage());
            response.sendRedirect(request.getContextPath()+"/");
        }else{
            logger.error(ex.toString());
            ex.printStackTrace();
            request.setAttribute("errorType", ex.getClass().getName());
            request.setAttribute("error", ex.toString());
            response.sendError(500, ex.getClass().getSimpleName());
        }
    }


    /**
     * 得到请求信息
     * @return
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
    }

    /**
     * 得到session回话信息
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }
}
